package com.heima.model;

import com.heima.domain.User;
import com.heima.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    //用户注册
    public int add(User user) {

        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            //获得连接
            conn = JDBCUtils.getConnection();

            //编写sql语句
            String sql = "insert into users(userName,password,sex,email)" + "values(?,?,?,?)";

            //预编译sql语句
            pstmt = conn.prepareStatement(sql);

            //设置参数
            pstmt.setString(1, user.getUserName());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getSex());
            pstmt.setString(4, user.getEmail());
            //执行sql语句
            result = pstmt.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(pstmt, conn);
        }
        return result;
    }


    public List findAll() {

        Connection conn = null;
        PreparedStatement pstmt = null;
        List userList = new ArrayList();
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();

            String sql = "select * from users";

            pstmt = conn.prepareStatement(sql);

            rs = pstmt.executeQuery();
            while (rs.next()) {
                Integer userId = rs.getInt("userId");
                String userName = rs.getString("userName");
                String password = rs.getString("password");
                String sex = rs.getString("sex");
                String email = rs.getString("email");
                User users = new User(userId, userName, password, sex, email);
                userList.add(users);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
        return userList;

    }

    public int delete(String userId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;
        try {
            conn = JDBCUtils.getConnection();

            String sql = "delete from users where userId=?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            result = pstmt.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(pstmt, conn);
        }

        return result;
    }

}

